<template>
  <div class="app-container  bg-gray">
    <transition name="fade-transform" mode="out-in">
      <router-view />
    </transition>
    <el-row v-if="isShow" class="box-1">
      <el-col :span="24">
        <el-card>
          <div class="header">
            <div>
              <el-select v-model="searchTerms.company" :loading="companyLoading" placeholder="部门" clearable @visible-change="getCompanyList">
                <el-option v-for="item in companyList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
              <el-select v-model="searchTerms.team" :loading="teamLoading" placeholder="团队" clearable @visible-change="getTeamList">
                <el-option v-for="item in teamList" :key="item.id" :label="item.branch_name" :value="item.id" />
              </el-select>
              <el-select v-model="searchTerms.status" placeholder="状态" clearable @visible-change="getTeamList">
                <el-option value="1" label="禁用"/>
                <el-option value="0" label="启用"/>
              </el-select>
              <el-input v-model="searchTerms.searchValue" placeholder="请输入姓名，手机或邮箱" class="search-input" />
              <el-button type="success" class="do-btn" icon="el-icon-search" @click="getData">搜索</el-button>
            </div>
            <div>
              <el-button v-if="queryMatch(11)" type="success" class="bg-green" icon="el-icon-circle-plus" @click="toModifyRoles('新增用户')">新增用户</el-button>
              <column-controller :check-items="th" @change="columnCheck" />
            </div>
          </div>
          <el-table v-loading="tableLoading" :data="tableData" :max-height="tableMaxHeight" border highlight-current-row @sort-change="handleSortChange">
            <el-table-column prop="id" label="ID" min-width="65" header-align="center" align="center" sortable />
            <el-table-column v-if="th[0].check" prop="name" label="用户名" min-width="90" header-align="center" align="center" />
            <el-table-column v-if="th[1].check" prop="sex" label="性别" min-width="80" header-align="center" align="center" sortable>
              <template slot-scope="scope">
                {{ scope.row.sex?scope.row.sex:'--' }}
              </template>
            </el-table-column>
            <el-table-column v-if="th[2].check" prop="mobile" label="手机" min-width="120" header-align="center" align="center" >
              <template slot-scope="scope">
                {{ scope.row.mobile?scope.row.mobile:'--' }}
              </template>
            </el-table-column>
            <el-table-column v-if="th[3].check" prop="email" label="邮箱" min-width="170" header-align="center" align="center" />
            <el-table-column v-if="th[4].check" prop="total_member" label="激活客户" min-width="100" header-align="center" align="center" />
            <el-table-column v-if="th[4].check" prop="total_customer" label="全部客户" min-width="100" header-align="center" align="center" />
            <el-table-column v-if="th[5].check&&queryMatch(127)" prop="bonus" label="账户余额" min-width="120" header-align="center" align="center" sortable="custom"/>
            <el-table-column v-if="th[6].check&&queryMatch(127)" prop="sale_bonus" label="奖金余额" min-width="120" header-align="center" align="center" sortable="custom"/>
            <el-table-column v-if="th[7].check&&queryMatch(108)" prop="company_name" label="部门名称" min-width="100" header-align="center" align="center" />
            <el-table-column v-if="th[8].check" prop="hiredate" label="入职时间" min-width="110" header-align="center" align="center" sortable >
              <template slot-scope="scope">
                {{ scope.row.hiredate ? parseTime(scope.row.hiredate, '{y}-{m}-{d}'): '' }}
              </template>
            </el-table-column>
            <el-table-column v-if="th[9].check" prop="create_time" label="最近登录时间" min-width="160" header-align="center" align="center" sortable />
            <el-table-column label="状态" min-width="80" header-align="center" align="center" fixed="right">
              <template slot-scope="scope">
                <div @click="queryMatch(12)?setState(scope.row):''">
                  <el-tag :type="scope.row.status===1?'danger':'primary'">{{ scope.row.status===1?'禁用':'启用' }}</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="220" header-align="center" align="center" fixed="right">
              <template slot-scope="scope">
                <el-tooltip content="用户面板" placement="top">
                  <el-button v-if="queryMatch(202)" type="warning" size="small" icon="el-icon-warning" circle
                             @click="toPersonal(scope.row)"/>
                </el-tooltip>
                <el-tooltip content="详细信息" placement="top">
                  <el-button v-if="queryMatch(12)" type="primary" size="small" icon="el-icon-search" circle
                             @click="toUserInfo(scope.row)"/>
                </el-tooltip>
                <el-tooltip content="钱包明细" placement="top">
                  <el-button v-if="queryMatch(186)" class="bg-green" type="warning" size="small" circle
                             @click="toWallet(scope.row)">
                    <svg-icon icon-class="wallet2"/>
                  </el-button>
                </el-tooltip>
                <el-tooltip content="删除用户" placement="top">
                  <el-button v-if="queryMatch(13)" type="danger" size="small" icon="el-icon-delete" circle
                             @click="toDelete(scope.row)"/>
                </el-tooltip>
                <el-tooltip v-if="queryMatch(218)" content="订单转移" placement="top">
                  <el-button type="info" size="small" icon="el-icon-share" circle @click="showTransfer(scope.row)"/>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page.sync="currentPage"
            :page-size="pageSize"
            :page-sizes="pageSizes"
            :total="total"
            class="pagination"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"/>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog :visible.sync="dialogVisible" title="订单转移" width="360px" class="dialog" center>
      <div class="content">
        <el-select v-model="transfer.toId" :loading="saleLoading" placeholder="请选择转移用户" filterable @visible-change="getSaleList">
          <el-option v-for="item in saleList" :key="item.value" :label="item.name" :value="item.id" />
        </el-select>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="toTransfer">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ColumnController } from '../../components'

import { handleSortChange, handleSizeChange, handleCurrentChange, columnCheck, parseTime } from '@/utils/table'
import { setViceToken } from '@/utils/auth'

export default {
  components: { ColumnController },
  data() {
    return {
      isShow: false,

      // 表格相关数据
      tableMaxHeight: document.documentElement.clientHeight - 280,
      th: [{ name: '用户名', check: true },
        { name: '性别', check: true },
        { name: '手机', check: true },
        { name: '邮箱', check: true },
        { name: '客户总数', check: true },
        { name: '账户余额', check: true },
        { name: '奖金余额', check: true },
        { name: '公司名称', check: true },
        { name: '入职时间', check: true },
        { name: '最近登录时间', check: true }],

      searchTerms: {
        team: '',
        company: '',
        searchValue: '',
        status: ''
      },
      dialogVisible: false,
      transfer: {
        id: '',
        toId: ''
      },

      // 下拉框相关数据
      companyLoading: false,
      companyList: [],
      teamLoading: false,
      teamList: [],
      saleLoading: false,
      saleList: [],

      // 表格相关参数
      tableLoading: false,
      currentPage: 1,
      pageSize: this.$store.getters.userInfo.pageSize,
      pageSizes: [10, 20, 50, 100, 1000],
      total: 0,
      tableData: []
    }
  },
  watch: {
    $route(to) {
      if (to.name === '系统用户') {
        this.getData()
        setTimeout(() => {
          this.isShow = true
        }, 500)
      } else {
        this.isShow = false
      }
    }
  },
  created() {
    if (this.$route.name === '系统用户') {
      this.isShow = true
      this.getTeamList(true);
      this.getData()
    }
  },

  methods: {
    handleCurrentChange, handleSizeChange, handleSortChange, columnCheck, parseTime, setViceToken,
    getData(order) {
      this.tableLoading = true
      order || (order = {})
      const url = 'user/list'
      const data = {
        page_no: this.currentPage,
        page_size: this.pageSize,
        search: this.searchTerms.searchValue,
        company_id: this.searchTerms.company,
        branch_id: this.searchTerms.team,
        status: this.searchTerms.status
      }
      order.sortName && (data.sortName = order.sortName)
      order.sortOrder && (data.sortOrder = order.sortOrder)
      this.$store.dispatch('GetConnect', { url, data }).then(res => {
        this.tableData = res.data.rows
        this.total = res.data.total
        this.tableLoading = false
      }).catch(e => {
        this.tableLoading = false
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    /**
     *  获取团队列表
     *  接口:'branch/all-list'
     */
    getTeamList(isShow) {
      if (isShow) {
        this.teamLoading = true
        const url = 'branch/all-list'
        this.$store.dispatch('GetConnect', { url }).then(res => {
          this.teamList = res.data
          this.teamLoading = false
          this.searchTerms.team = this.$route.query.team && parseInt(this.$route.query.team);
        }).catch(e => {
          this.teamLoading = false
          this.$message.error(e.msg + ',请刷新或联系管理员')
        })
      }
    },

    /**
     *  获取公司列表
     *  接口:'company/all-list'
     */
    getCompanyList(isShow) {
      if (isShow) {
        this.companyLoading = true
        const url = 'company/all-list'
        this.$store.dispatch('GetConnect', { url }).then(res => {
          this.companyList = res.data
          this.companyLoading = false
        }).catch(e => {
          this.companyLoading = false
          this.$message.error(e.msg + ',请刷新或联系管理员')
        })
      }
    },

    /**
     *  获取销售列表
     *  接口:'company/all-list'
     */
    getSaleList(query) {
      if (query !== '') {
        this.saleLoading = true
        const url = 'user/all-list'
        this.$store.dispatch('GetConnect', { url }).then(res => {
          this.saleList = res.data
          this.saleLoading = false
        }).catch(e => {
          this.saleLoading = false
          this.$message.error(e.msg + ',请刷新或联系管理员')
        })
      }
    },

    /**
     * 设置当前用户的账号状态
     * row: 当前点击的行的数据
     */
    setState(row) {
      row.status = row.status === 0 ? 1 : 0
      const url = 'user/ajax/' + row.id
      const data = { action: 'update_status', status: row.status }
      this.$store.dispatch('GetConnect', { url, data }).then(res => {
        this.$message.success('修改用户账号状态成功，状态：' + (row.status === 0 ? '启用' : '禁用'))
      }).catch(e => {
        row.status = row.status === 0 ? 1 : 0
        this.$message.error('修改用户状态失败，请刷新或联系管理员')
      })
    },

    toPersonal(row) {
      const url = 'user/switchUser?id=' + row.id
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.setViceToken(res.data.token)
        this.$store.dispatch('SetToken', res.data.token).then(() => {
          const loading = this.$loading()
          this.$router.push({ path: '/homepage/index' })
          setTimeout(function() {
            location.reload()
            loading.close()
          }, 800)
        })
      }).catch(() => {
        this.$message.error('跳转失败，请刷新或联系管理员')
      })
    },

    // 跳转用户钱包明细
    toWallet(row){
      this.$router.push({
        path: '/wallet/details',
        query: { id: row.id }
      });
    },

    /**
     * 跳转用户详情
     * title: 新增/修改
     * row: 当前点击的行的数据,为空时为新增
     */
    toUserInfo(row) {
      this.isShow = false
      this.$router.push({
        path: '/permissions/users/userInfo',
        query: { id: row.id }
      })
    },

    /**
     * 跳转用户修改页面
     * title: 新增/修改
     * row: 当前点击的行的数据,为空时为新增
     */
    toModifyRoles(title, row) {
      this.isShow = false
      const query = { title: title }
      row && (query.id = row.id)
      this.$router.push({
        path: '/permissions/users/modifyUser',
        query: query
      })
    },

    /**
     * 删除用户
     * row: 当前点击的行的数据user/delete
     */
    toDelete(row) {
      this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const url = 'user/delete/' + row.id
        this.$store.dispatch('GetConnect', { url }).then(res => {
          this.$message.success('删除成功!')
          this.getData()
        }).catch(e => {
          this.$message.error(e.msg + '，请刷新或联系管理员')
        })
      })
    },

    /**
     * 显示用户订单转移弹窗
     * row: 当前点击的行的数据
     */
    showTransfer(row) {
      this.dialogVisible = true
      this.transfer.id = row.id
    },

    /**
     * 用户订单转移
     */
    toTransfer() {
      if (this.transfer.toId === '' || this.transfer.toId === null) {
        this.$message.error('请选择要转移至哪位销售')
      } else {
        this.$confirm('此操作将转移该用户下所有客户及订单, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const url = 'user/exchange'
          const data = {
            exchange_user: this.transfer.toId,
            uid: this.transfer.id
          }
          this.$store.dispatch('GetConnect', { url, data }).then(res => {
            this.$message.success('转移成功!')
            this.getData()
          }).catch(e => {
            this.$message.error(e.msg + '，请刷新或联系管理员')
          })
        })
      }
    }
  }
}
</script>

<style lang="scss" type="text/scss" scoped>
@import '../../../styles/index.scss';
.box-1 {
  .header {
    @include flex-row(center, space-between);
    padding-bottom: 15px;
    div {
      @include flex-row(center, flex-start);
      flex-wrap: wrap;
    }
    .el-select {
      padding-right: 15px;
      width: 180px;
    }
    .search-input {
      width: 240px;
    }
    .do-btn {
      @extend .bg-green;
      margin-left: 6px;
    }
  }
}
.dialog {
  .content{
    text-align: center
  }
}
.el-tag {
  cursor: pointer;
}
</style>
